package com.example.myproject.service.serviceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.myproject.model.Right;
import com.example.myproject.model.User;
import com.example.myproject.model.Role;
import com.example.myproject.model.UserRoleRelation;
import com.example.myproject.repository.RightRepository;
import com.example.myproject.repository.UserRepository;
import com.example.myproject.repository.RoleRepository;
import com.example.myproject.repository.UserRoleRelationRepository;
import com.example.myproject.service.RightService;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RightServiceImpl implements RightService {

    private static final Logger logger = LoggerFactory.getLogger(RightServiceImpl.class);

    @Autowired
    private RightRepository rightRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRelationRepository userRoleRelationRepository;

    @Override
    public Right assignRight(Right right) {
        logger.debug("分配权限：{}", right);
        Right savedRight = rightRepository.save(right);
        logger.debug("权限分配成功，权限ID：{}", savedRight.getId());
        return savedRight;
    }

    @Override
    public void removeRight(int id) {
        logger.debug("删除权限，权限ID：{}", id);
        rightRepository.deleteById(id);
        logger.debug("权限删除成功，权限ID：{}", id);
    }

    @Override
    public Right getRight(String name) {
        logger.debug("获取权限，权限名：{}", name);
        Right right = rightRepository.findByUserName(name).orElse(null);
        if (right != null) {
            logger.debug("权限获取成功，权限ID：{}", right.getId());
        } else {
            logger.debug("权限获取失败，权限名：{}", name);
        }
        return right;
    }

    @Override
    public void assignRolesToUserByName(String userName, Set<String> roleNames) {
        logger.debug("分配角色给用户，用户名：{}，角色名集合：{}", userName, roleNames);
        User user = userRepository.findByUsername(userName);
        if (user != null) {
            logger.debug("用户找到，用户ID：{}", user.getId());
            List<UserRoleRelation> existingRelations = userRoleRelationRepository.findByUser(user);
            userRoleRelationRepository.deleteAll(existingRelations);
            logger.debug("删除用户当前的所有角色关系，数量：{}", existingRelations.size());

            for (String roleName : roleNames) {
                Role role = roleRepository.findByName(roleName);
                if (role != null) {
                    UserRoleRelation userRoleRelation = new UserRoleRelation();
                    userRoleRelation.setUser(user);
                    userRoleRelation.setRole(role);
                    userRoleRelationRepository.save(userRoleRelation);
                    logger.debug("角色分配成功，角色名：{}", roleName);
                } else {
                    logger.warn("角色未找到，角色名：{}", roleName);
                }
            }
        } else {
            logger.warn("用户未找到，用户名：{}", userName);
        }
    }

    @Override
    public List<Role> getUserRoles(String userName) {
        logger.debug("获取用户角色，用户名：{}", userName);
        User user = userRepository.findByUsername(userName);
        if (user != null) {
            List<Role> roles = userRoleRelationRepository.findByUser(user).stream()
                    .map(UserRoleRelation::getRole)
                    .collect(Collectors.toList());
            logger.debug("获取用户角色成功，角色数量：{}", roles.size());
            return roles;
        } else {
            logger.warn("用户未找到，用户名：{}", userName);
            return Collections.emptyList();
        }
    }
}
